/*
 * miniFreeRTOS SOC System emulation.
 *
 * Copyright (c) 2024- yanl1229@163.com.
 * Written by yanl1229
 *
 * This code is licensed under the GPL.
 */
#include "signal.h"
#include "mm.h"
#include "task.h"

void signal_send(struct signal *sg)
{
    sg->signal_pending = 1;
}

void signal_delete(struct signal *sg)
{
    if (sg != NULL)
        kfree(sg);
}

static void siganl_task_fn(void *args)
{
    struct signal *sg = (struct signal *)args;

    for (; ;)
    {
        if (sg->signal_pending == 0)
            continue;

        sg->signal_pending = 0;
        if (sg->action != NULL)
             sg->action(sg->ptr);
    }
}

struct signal *signal_create(char *name, void (*action)(void *ptr), void *ptr)
{
    struct signal *sg = NULL;


    sg = (struct signal *)kmalloc(sizeof(struct signal));

    if (sg == NULL)
        return NULL;

    sg->action = action;
    sg->ptr = ptr;
    sg->signal_pending = 0;

    /* 创建信号处理任务 */
    task_create(siganl_task_fn,
                               name,
                               CONFIG_MINIMAL_STACK_SIZE,
                               sg,
                               CONFIG_TASK_IDLE_PRIORITY);
    return sg;
}

